/*  
 * 2011/1/5 add the IP address
 * 2011/1/6 want to add count third Wensday 
 * 2011/1/19 檢查是否為結算日 並假日檢查加入
 */

import java.util.Date;
import java.util.StringTokenizer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.*;
import java.io.*;
import java.util.Calendar;

import org.omg.CORBA.ValueBaseHolder;
public class checkStockDate {
		static String Today="";//紀錄今天日期
		static final String[] Webdns={"http://money.hinet.net/z/ze/zec/zec.djhtm","http://www.emega.com.tw/z/ze/zeb/zeb.asp.htm"};
		static int[] prices=new int[4];//分紀錄開盤 最高 最低 收盤 四種價錢
		static final String[] ShowName={"catalog.digitalachives.tw"};
	    static final int[] port={80};
	    static boolean[] WebNodeStatus={false};
	    static String[] WebAlive={"Dead"};
		static Date d=new Date();
	    static String s;
	    static private int try_number=1;
	    static DateFormat formateYearMonthDay=new SimpleDateFormat("yyyy-MM-dd");//設定時間格式HH 24小時時制
	    static DateFormat formate1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定時間格式HH 24小時時制
//	    static conMySQL con=null;
	    static java.text.DecimalFormat df=new java.text.DecimalFormat("#.##");//小數點後兩位
	    static java.text.DecimalFormat df2=new java.text.DecimalFormat("#.###");//小數點後三位
	    static String OutBalanceDataWebPage="http://www.taifex.com.tw/chinese/3/7_12_2.asp";
		static int Fist_Dealers_Line=379;
		static int First_In_Trust_Line=403;
		static int First_Forgein_Line=427;
		//以下陣列分別記錄三大法人在期貨與OP的多[0]空[1]未平倉金額(千元)
		static int[] Foreign_Futurn=new int[2],Dealers_Futurn=new int[2],In_Trust_Futurn=new int[2];
		static int[] Foregin_Op=new int[2],Dealers_Op=new int[2],In_Trust_Op=new int[2];
		static String mailmessage="";
//		JavaMailDemo mail=new JavaMailDemo();
		static boolean alreadySentErrMeaasge=false;//查看是否已經發錯誤訊息通知
	    public static void main(String[] args) { 
//			con=new conMySQL();
//			con.setConnectionToMysql();
			checkStockDate check=new checkStockDate();
			Today=formateYearMonthDay.format(new Date());
			//<td align="center" bgcolor="#FFFfff" nowrap>14:30</td>
			String pattern1=
			mailmessage="The Date is "+Today+"\r\n"+"Today message is at list:"+"\r\n";
			initAllIntNumber();
//			check.GetStockTime();
			check.getStockPrice();
//			check.getTodayPrice("9906");
								

			
			}


		
		



		public String[] getTodayPrice(String id) {
			String [] value=new String[3];
			try{
				URL url=new URL("http://tw.stock.yahoo.com/q/q?s="+id);
				BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"MS950"));
				String line;
				int count=0;
		    	String pattern1 = "((.)*<td){1}.(align=){1}(.)*(nowrap>){1}(<b>|<font color=#ff0000>)?";
		    	String pattern2 = "(</b>)?(</td>){1}";
//		    	String pattern3="(△|▽|<font color=#000000>)?";
		    	while((line=reader.readLine())!=null){
		    		if(line.indexOf("<td align=\"")!=-1){
		    			count++;
		    			line=line.replaceAll(pattern1, "").replaceAll(pattern2, "");
		    			System.out.println(line);
		    			switch (count) {
						case 1:
							//時間
							value[0]=line;
							break;
						case 2:
							//成交價
							value[1]=line;
							break;
						case 5:
							//漲跌停
//							System.out.println(line);
							value[2]=returnWord(line);
							System.out.println("Return:"+value[2]);
							break;
						}
		    		}
		    	}
			}catch (MalformedURLException e) {
				// TODO: handle exception
			}catch (IOException e) {
				// TODO: handle exception
			}
			return value;
		}
		public String returnWord(String line){
			System.out.println(line);
	    	String pattern="(△|▽|<font color=#000000>|▲)?";
			if(line.indexOf("△")!=-1){
				return ("UP "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▽")!=-1){
				return ("DOWN "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▲")!=-1){
				return ("M_UP "+line.replaceAll(pattern, ""));
			}else if(line.indexOf("▼")!=-1){
				return("M_DOWN "+line.replaceAll(pattern, ""));
			}else{
				return(line.replaceAll(pattern, ""));
			}
			
		}
		
		public void getStockPrice(){
			try{ 			
				URL url=new URL(Webdns[1]);
				int count=0;
				s=formate1.format(new Date());
				String tempDate=formateYearMonthDay.format(new Date());
				while(count<try_number){
		
					int countline=0;
					//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"MS950"));
					String line;
			    	System.out.println("Get Information form Web!");
			    	String pattern1 = "(<TD|<td){1}.(class=\"t3){1}(n|t){1}(1|0)?(\"){1}(>){1}";
			    	String pattern2 = "(</TD>|</td>){1}";
			    	String pattern3 = "(GenLink2stk){1}|<a href=\"javascript:Link2Stk(.)*\">";
			    	String pattern4 = "(,){1}";
			    	String pattern4_1="[0-9]{1,4}[0-1]{1}";
			    	String pattern5 = "(;)?(</a>)?";
			    	String pattern6="((.)*\\((AS)){1}|\\)";
			    	int linecount=0;
			    	while((line=reader.readLine())!=null){
						if(line.indexOf("GenLink2stk")!=-1|line.indexOf("javascript:Link2Stk")!=-1){
//							linecount=0;
							String[] newline=line.replaceAll(pattern3, "").split(pattern4);
							String[] value=new String[2];
							for(int i1=0;i1<newline.length;i1++){
								if(i1==0){
									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									System.out.print(" 代號："+value[0]);
//									value[0]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
								}else{
									value[1]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
									System.out.print(" 名稱："+value[1]);
//									value[1]=newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,"");
								}
								
								//System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
							}
//							System.out.println(line.replaceAll(pattern2, ""));
						}
						else 
							if(line.indexOf("<TD class=\"t3")!=-1|line.indexOf("<td class=\"t3")!=-1){
							linecount++;
							String word="";
							int modnum=(linecount-1)%8;
							switch(modnum){
								case 0:
									word="日期：";
									break;
								case 2:
									word=" 現金股利：";
									break;
								case 3:
									word=" 盈餘配股：";
									break;
								case 4:
									word=" 公績配股:";
									break;
								case 5:
									word=" 現金增資:";
									break;
								case 6:
									word=" 承銷價:";
									break;
								case 7:
									linecount=0;
									word="現金股利發放日:";
									break;
							}
							
							String httpword=line.replaceAll(pattern1, "").replaceAll(pattern2, "");
							if(httpword.equals("&nbsp;")){
								httpword="無資訊";
							}
							if(modnum==7){
								System.out.println(" "+modnum+word+httpword);
							}else if (modnum==1) {
							}else{
								if(!httpword.contains("<tr>")){
									System.out.print(" "+modnum+":"+word+httpword);
								}
							}
						
						}
						
					}
					reader.close();
					count++;
				}
				}catch (Exception e) {

			}

	
			
		}
		
		

		public void GetStockTime(){
			for(int i=0;i<Webdns.length;i++){	
				try{ 			
					URL url=new URL(Webdns[i]);
					int count=0;
					s=formate1.format(new Date());
					String tempDate=formateYearMonthDay.format(new Date());
					while(count<try_number){
						int countline=1;
						//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
						BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream(),"MS950"));
						String line;
				    	System.out.println("Get Information form Web!");
				    	String pattern1 = "(<TD|<td){1}.(class=\"t3){1}(n|t){1}(1|0){1}(_rev)?(\"){1}(.)?(nowrap)?(>){1}";
				    	String pattern2 = "(</TD>|</td>){1}";
				    	String pattern3 = "(GenLink2stk){1}";
				    	String pattern4 = "(,){1}";
				    	String pattern5 = "(;)?";
				    	String pattern6="((.)*\\((AS)){1}|\\)";
				    	int linecount=5;
				    	while((line=reader.readLine())!=null){
							if(line.indexOf("GenLink2stk")!=-1){
//								linecount=0;
								String[] newline=line.replaceAll(pattern3, "").split(pattern4);
								for(int i1=0;i1<newline.length;i1++){
									if(i1==0){
										System.out.print("代號：");
									}else{
										System.out.print(" 名稱：");
									}
									System.out.print(newline[i1].replace("'", "").replaceAll(pattern5, "").replaceAll(pattern6,""));	
								}
//								System.out.println(line.replaceAll(pattern2, ""));
							}
							else if(line.indexOf("<TD class=\"t3")!=-1|line.indexOf("<td class=\"t3")!=-1){
								String word="";
								switch(linecount%4){
									case 0:
										word=" 開會時間：";
										break;
									case 1:
										word=" 開會地點：";
										break;
									case 2:
										word=" 改選:";
										break;
									case 3:
										word=" 性質:";
										break;
								}
								
								if(linecount%4!=3){
									System.out.print(linecount+":"+word+line.replaceAll(pattern1, "").replaceAll(pattern2, ""));
								}else {
									System.out.println(linecount+":"+word+line.replaceAll(pattern1, "").replaceAll(pattern2, ""));
								}
								linecount++;
							}
							countline++;
						}
						reader.close();
						count++;
					}
					}catch (Exception e) {

				}
			}
			
		}
		/*
		 * 查詢期交所上尚三大法人未平倉部位 並將資料插入資料庫
		*/
		public void InsertTodayOutBalanceDataInfo(){

				String tempDate=formateYearMonthDay.format(new Date());
				try{        
					URL url=new URL(OutBalanceDataWebPage);
					int countline=1;
					s=formate1.format(new Date());
					//HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream()));
					String line;
				    System.out.println("Get Outstanding balance data Information form Web!");
					while((line=reader.readLine())!=null){
						getOutcomingBalFromCountLine2(countline,line);						
						countline++;
						}
					reader.close();
						
					

				}catch (Exception e) {
					
					e.printStackTrace();
					System.out.println("Can't get price!! --- Time is "+s);
				}
		}


		
		
		/*
		 * 將期交所的網頁資料館換成三大法人部位資訊
		 */
		public static  void getOutcomingBalFromCountLine2(int countline,String line){			
			/*
			int Fist_Dealers_Line=390;
			int First_In_Trust_Line=414;
			int First_Forgein_Line=438;
			*/
			if(countline==Fist_Dealers_Line){
				System.out.println(line);
				Dealers_Futurn[0]=returnOutstandingBal(line);
			}else if(countline==(Fist_Dealers_Line+2)){
	
				System.out.println(line);
				Dealers_Op[0]=returnOutstandingBal(line);
			}
			else if(countline==(Fist_Dealers_Line+8)){
				System.out.println(line);
				Dealers_Futurn[1]=returnOutstandingBal(line);
			}else if(
			countline==(Fist_Dealers_Line+10)){
				//System.out.println(line);
				Dealers_Op[1]=returnOutstandingBal(line);
			}
			else if(countline== First_In_Trust_Line){
				//System.out.println(line);
				In_Trust_Futurn[0]=returnOutstandingBal(line);
			}else if(countline==(First_In_Trust_Line+2)){
			
				//System.out.println(line);
				In_Trust_Op[0]=returnOutstandingBal(line);
			}
			else if(countline==(First_In_Trust_Line+8)){
				//System.out.println(line);
				In_Trust_Futurn[1]=returnOutstandingBal(line);
			}else if(countline==(First_In_Trust_Line+10)){
				In_Trust_Op[1]=returnOutstandingBal(line);
			}else if(countline==First_Forgein_Line)
			{
				//System.out.println(line);
				Foreign_Futurn[0]=returnOutstandingBal(line);
			}
			else if(countline==(First_Forgein_Line+2)){
				//System.out.println(line);
				Foregin_Op[0]=returnOutstandingBal(line);
			}
			else if(countline==(First_Forgein_Line+8)){
				//System.out.println(line);
				Foreign_Futurn[1]=returnOutstandingBal(line);
				//System.out.println("Foreign_Futurn[1]: "+Foreign_Futurn[1]);
			}
			else if(countline==First_Forgein_Line+10){
				//System.out.println(line);
				Foregin_Op[1]=returnOutstandingBal(line);
				
			}		
		}
		public static  void StockInfoFromCountLine(int countline,String line){
			//int i=countline;
			int Baseline=988;
			int finalline=1002;
			//switch (countline) {
			if (countline==Baseline){
				//System.out.println(countline+" : "+line);
				prices[0]=returnPrices(line);
				//Dealers_Futurn[0]=returnOutstandingBal(line);
				//break;
			}
			else if(countline==(Baseline+1)){
				//System.out.println(countline+" : "+line);
				prices[1]=returnPrices(line);
				//Dealers_Op[0]=returnOutstandingBal(line);
				//break;
			}
			else if(countline==(Baseline+2)){
			
				//System.out.println(countline+" : "+line);
				prices[2]=returnPrices(line);
				//Dealers_Futurn[1]=returnOutstandingBal(line);
				//break;
			}else if(countline==finalline){
				prices[3]=Integer.valueOf(line.replaceAll("\\s", ""));
			}
			
		
		}
		public static  void SettleStockInfoFromCountLine(int countline,String line){
			//int i=countline;
			int Baseline=974;
			//int finalline=411;
			//switch (countline) {
			if (countline==Baseline){
				//System.out.println(countline+" : "+line);
				prices[0]=returnPrices(line);
				//Dealers_Futurn[0]=returnOutstandingBal(line);
				//break;
			}
			else if(countline==(Baseline+1)){
				//System.out.println(countline+" : "+line);
				prices[1]=returnPrices(line);
				//Dealers_Op[0]=returnOutstandingBal(line);
				//break;
			}
			else if(countline==(Baseline+2)){
			
				//System.out.println(countline+" : "+line);
				prices[2]=returnPrices(line);
				//Dealers_Futurn[1]=returnOutstandingBal(line);
				//break;
			}else if(countline==Baseline+3){
				prices[3]=returnPrices(line);
			}
			
		
		}
		
		
		
		public static  void StockInfoFromCountLine2(int countline,String line){
			//int i=countline;
			
			switch (countline) {
			case 397:
				//System.out.println(countline+" : "+line);
				prices[0]=returnPrices(line);
				//Dealers_Futurn[0]=returnOutstandingBal(line);
				break;
			case 398:
				//System.out.println(countline+" : "+line);
				prices[1]=returnPrices(line);
				//Dealers_Op[0]=returnOutstandingBal(line);
				break;
			case 399:
				//System.out.println(countline+" : "+line);
				prices[2]=returnPrices(line);
				//Dealers_Futurn[1]=returnOutstandingBal(line);
				break;
			case 411:
				//System.out.println(countline+" : "+line);
				//System.err.println("長度:"+line.length());
				//System.out.println(line.replaceAll("\\s", ""));
				prices[3]=Integer.valueOf(line.replaceAll("\\s", ""));
				//Dealers_Op[1]=returnOutstandingBal(line);
				break;
			}
		
		}
		
		

		
		public static int returnPrices(String str){
			//System.out.println("str is "+str);
			String sym="<TD align=right class=\"\">";
			String[] temp=getStrings(str,sym);
			double[] Tempprices=new double[4];
			System.out.println("temp: "+str);
			int tempPrice=Integer.valueOf(temp[2]);
			
			
	        /*
			java.util.Vector<String> VecterNumber=checkStrCondition(temp);
			for (int i = 4; i < VecterNumber.size()-1; i++) {
				String ttt=VecterNumber.get(i).replace(",", "");
				System.out.println("ttt is "+ttt);
				Double DoubleTemp=Double.valueOf(VecterNumber.get(i).replace(",", ""));
				//System.out.println("1: "+VecterNumber.get(i)+" - "+Double.valueOf(VecterNumber.get(i))+" - "+DoubleTemp);
				prices[i-4]=DoubleTemp;
			}
			*/
			return tempPrice;
		}
		public static int returnOutstandingBal(String str){
			//System.out.println("str is "+str);
			String sym="<TD align=right nowrap bordercolordark=\"#ffffff\" bgcolor=\"#FFFFFF\" class=\">";
			String[] temp=getStrings(str,sym);
		    int prices=Integer.valueOf(temp[2].replace(",", ""));
		    //System.out.println(prices);
	        /*java.util.Vector<String> VecterNumber=checkStrCondition(temp);
			for (int i = 3; i < VecterNumber.size()-1; i++) {
				String ttt=VecterNumber.get(i).replace(",", "");
				Double DoubleTemp=Double.valueOf(VecterNumber.get(i).replace(",", ""));
				//System.out.println("1: "+VecterNumber.get(i)+" - "+Double.valueOf(VecterNumber.get(i))+" - "+DoubleTemp);
				prices[i-3]=DoubleTemp;
			}
			*/
			return prices;
		}
		//get WAN IP from http://checkip.dyndns.org
		public String readIP(){
			String result=null;
			try{
			URL url=new URL("http://checkip.dyndns.org");
			BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream()));
			String line;
	    	//System.out.println("Get Information form Web!");
			while((line=reader.readLine())!=null){
				String[] temp=getStrings(line, ":");
				//System.out.println(temp[0]);
				//System.out.println(temp[1]);
				temp=getStrings(temp[1], "<");
				result=temp[0].replace(" ", "");
				//System.out.println(temp[1]);
			}
			}catch(Exception e){
				e.printStackTrace();
				
			}
			return result;
		}	
		
		
		public  static String[] getStrings(String oldstr,String sym){
			String[] a=null;
			StringTokenizer st=new StringTokenizer(oldstr,sym);
			int n=st.countTokens();
			a=new String[n];
			int i=0;
			while(st.hasMoreTokens()){
				a[i]=st.nextToken();
				i++;
			}
			return a;
		}
		
		public  static java.util.Vector<String> checkStrCondition(String[] oldArray){
			String[] a=null;
			java.util.Vector<String> temp=new java.util.Vector<String>(0);
			for (int i = 0; i < oldArray.length; i++) {
				if((oldArray[i].indexOf("#")==-1)&&(oldArray[i].length()>6)){
					temp.add(oldArray[i]);
				}
			}
			return temp;
		}
		//將千元轉換成億
		public static String changeToE(int number){
			 return df2.format((Double.valueOf(number))/100000);
		}
		public static void initAllIntNumber(){
			for (int i = 0; i < In_Trust_Futurn.length; i++) {
				Foreign_Futurn[i]=0;
				Foregin_Op[i]=0;
				Dealers_Op[i]=Dealers_Futurn[i]=0;
				//System.out.println(Dealers_Futurn[i]);
				In_Trust_Futurn[i]=0;
				In_Trust_Op[i]=0;
				
			}
			//System.out.println("AAAA: "+Dealers_Futurn[0]+" -- "+Dealers_Op[0]);
		}
		//檢查是否為星期六或是日（是的話就不作）
		public boolean CheckWeeks(){
		    DateFormat formateDay2=new SimpleDateFormat("E",java.util.Locale.ENGLISH);//設定時間格式(轉換成millsec)
		    Date date=new Date();
		    String week=formateDay2.format(date);
			if(week.equals("Sat")||week.equals("Sun")){
				return false;
			}else{
				return true;
			}
			
		}
		




}
